package mhl.DAO;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import practice_0614.JDBC_Druid;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class basicDao<T> {

    private QueryRunner qr = new QueryRunner();


    public  List<T> getMany(String sql, Class<T> clazz, Object... param) {
        Connection con = JDBC_Druid.getConnection();
        List<T> list;
        try {
            list = qr.query(con, sql, new BeanListHandler<>(clazz), param);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBC_Druid.close(null, con, null);
        }

        return list;
    }

    public T getSingle(String sql,Class<T> clazz, Object... param) {
        Connection con = JDBC_Druid.getConnection();
        try {
           return qr.query(con, sql, new BeanHandler<T>(clazz), param);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBC_Druid.close(null, con, null);
        }

    }

    public Object getObject(String sql,Object... param){
        Connection con =  JDBC_Druid.getConnection();
        try {
            return qr.query(con, sql, new ScalarHandler<T>(), param);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBC_Druid.close(null, con, null);
        }
    }

    public int updateTable(String sql,Object... param){
        Connection con = JDBC_Druid.getConnection();
        try {
            return qr.update(con,sql,param);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            JDBC_Druid.close(null,con,null);
        }


    }



}
